package curl

import (
	"fmt"
	"io/ioutil"
	"jsjb/tools"
	"log"
	"net/http"
	"net/url"
	"strings"
)

var defaultDomain = "https://www.abc.com"

const HttpProxyUrl = "http://127.0.0.1:8888"

type Curl struct {
	url, domain string
	data        map[string]string
}

// New get 请求接口
func New(url, domain string, data map[string]string) *Curl {
	if domain == "" {
		domain = defaultDomain
	}
	c := &Curl{
		url:    url,
		domain: domain,
		data:   data,
	}
	return c

}
func (c *Curl) Get() []byte {
	resp, err := http.Get(c.domain + c.url)
	if err != nil {
		fmt.Printf("get failed, err:%v\n", err)
		log.Fatalln(err)
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("read from resp.Body failed, err:%v\n", err)
		log.Fatalln(err)
	}
	return body
}

func (c *Curl) Post(headerType string) []byte {
	ProxyURL, _ := url.Parse(HttpProxyUrl)
	client := &http.Client{
		//设置代理
		Transport: &http.Transport{
			Proxy: http.ProxyURL(ProxyURL),
		},
	}
	var req *http.Request
	if headerType == "www" {
		//发送请求
		req, _ = http.NewRequest("POST", c.domain+c.url, strings.NewReader(tools.MapToQuery(c.data)))

		//设置请求头信息
		req.Header.Add("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
	} else if headerType == "json" {
		//发送请求
		req, _ = http.NewRequest("POST", c.domain+c.url, strings.NewReader(tools.MapToQuery(c.data)))

		//设置请求头信息
		req.Header.Add("Content-Type", "application/json")
	}

	resp, err := client.Do(req)
	if err != nil {
		log.Fatalln(err)
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatalln(err)
	}
	return body
}
func (c *Curl) PostJson(params string) []byte {
	ProxyURL, _ := url.Parse(HttpProxyUrl)
	client := &http.Client{
		//设置代理
		Transport: &http.Transport{
			Proxy: http.ProxyURL(ProxyURL),
		},
	}
	var req *http.Request

	//发送请求
	req, _ = http.NewRequest("POST", c.domain+c.url, strings.NewReader(params))

	//设置请求头信息
	req.Header.Add("Content-Type", "application/json")

	resp, err := client.Do(req)
	if err != nil {
		log.Fatalln(err)
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatalln(err)
	}
	return body
}
